<template>
  <div>
    <section class="section-title">
      <h3>Invoice details</h3>
    </section>
    <section class="detail-info-form">
      <Form ref="shipmentForm" :model="shipmentForm" :rules="ruleValidate" :label-width="160" class="shipment-form">
        <FormItem label="Fullfillment" prop="fullfillment">
          <Select v-model="shipmentForm.fullfillment" placeholder="Choose Fullfillment" style="max-width: 300px;">
            <Option value="Hong Kong">Hong Kong</Option>
            <Option value="Italy">Italy</Option>
          </Select>
        </FormItem>
        <FormItem label="Supplier Courier" prop="supplierCourier">
          <Select v-model="shipmentForm.supplierCourier" placeholder="Choose Courier" style="max-width: 300px;">
            <Option value="DHL">DHL</Option>
            <Option value="Italy">Fedex</Option>
          </Select>
        </FormItem>
        <FormItem label="Dispatch Date" prop="dispatchDate">
          <DatePicker type="date" placeholder="Select date" v-model="shipmentForm.dispatchDate" style="width: 300px;"></DatePicker>
        </FormItem>
        <FormItem label="ETA" prop="ETA">
          <DatePicker type="date" placeholder="Select date" v-model="shipmentForm.ETA" style="width: 300px;"></DatePicker>
        </FormItem>
        <FormItem label="Tracking No." prop="tracking">
          <Input v-model="shipmentForm.tracking" placeholder="Enter something..." style="max-width: 300px;"></Input>
        </FormItem>
        <FormItem label="Shipping fee" prop="shippingFee">
          <Input v-model="shipmentForm.shippingFee" placeholder="Enter something..." style="max-width: 300px;"></Input>
        </FormItem>
        <FormItem label="Invoice No." prop="invoice">
          <Input v-model="shipmentForm.invoice" placeholder="Enter something..." style="max-width: 300px;"></Input>
        </FormItem>
        <FormItem label="invoiceDate" prop="invoiceDate">
          <DatePicker type="date" placeholder="Select date" v-model="shipmentForm.invoiceDate" style="width: 300px;"></DatePicker>
        </FormItem>
        <FormItem label="Invoice Attachment" prop="invoiceAttachment">
          <p>（Up to 5 files,support PDF, Excel formats.）</p>
          <section class="invoice-wrapper">
            <div class="invoice-attachment" v-for="(item, index) in uploadList" :key="index">
              <!--<template v-if="item.status === 'finished'">-->
              <template v-if="true">
                <div class="invoice-attachment-file">
                  <!--<img :src="item.default_img">-->
                  <img src="../assets/images/pdf-default-icon.png" alt="" v-if="item.default_img == 'pdf'">
                  <img src="../assets/images/excel-default-icon.jpg" alt="" v-if="item.default_img == 'excel'">
                  <p class="invoice-attachment-icons">
                    <Icon type="ios-cloud-download-outline" class="icon" />
                    <Icon type="ios-trash-outline" class="icon" @click.native="handleRemove(item)" />
                  </p>
                </div>
                <p class="invoice-attachment-name">{{item.name}}</p>
              </template>
              <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <Upload
              ref="upload"
              :show-upload-list="false"
              :default-file-list="defaultList"
              :on-success="handleSuccess"
              :format="['pdf','xlsx']"
              :on-format-error="handleFormatError"
              :before-upload="handleBeforeUpload"
              multiple
              type="drag"
              action="http://mock-data-data-api/api/supplier-PO/wait-to-ship/create-ship/upload-invoice"
              style="display: inline-block;width:58px;">
              <div style="width: auto;height:58px;line-height: 58px;">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              </div>
            </Upload>
          </section>
        </FormItem>
        <FormItem label="Notes" prop="notes">
          <Input v-model="shipmentForm.notes" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="Enter something..." style="max-width: 300px;"></Input>
        </FormItem>
        <FormItem  v-if="shipAction=='create'">
          <Button @click="$router.push('/supplier-PO/wait-to-ship-WH')">Go Back</Button>
          <Button style="margin-left: 8px" type="primary" @click="submitShipFrom('shipmentForm')">Submit</Button>
        </FormItem>

        <FormItem  v-if="shipAction=='edit'">
          <Button @click="$router.push('/supplier-PO/shipped')">Go Back</Button>
          <Button style="margin-left: 8px"  type="primary" @click="submitEditShipFrom('shipmentForm')">Confirm</Button>
        </FormItem>
      </Form>
    </section>
    <Modal v-model="createShipmentSuccessful" width="360">
      <p slot="header" style="text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>confirmation</span>
      </p>
      <div style="text-align:center">
        <p>Go back wait to ship!</p>
      </div>
      <div slot="footer">
        <Button type="success" size="large" long @click="goBack('/supplier-PO/shipped')">go to Shipped</Button>
      </div>
    </Modal>
    <Modal v-model="editShipmentSuccessful" width="360">
      <p slot="header" style="text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>confirmation</span>
      </p>
      <div style="text-align:center">
        <p>Go back wait to ship!</p>
      </div>
      <div slot="footer">
        <Button type="success" size="large" long @click="goBack('/supplier-PO/shipped')">go Back</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex';
  import { modalInstance } from '@/components/mixin';
  import { createShipment } from '@/api/index';
  export default {
  	name: 'ShipmentForm',
    props: ['shipmentList', 'shipmentForm', 'shipAction'],
    mixins: [ modalInstance ],
    data () {
  		return {
        createShipmentSuccessful: false,
        editShipmentSuccessful: false,
        ruleValidate: {
          fullfillment: [
            { required: true, message: 'Please select fullfillment', trigger: 'change' }
          ],
          supplierCourier: [
            { required: true, message: 'Please select supplier courier', trigger: 'change' }
          ],
          dispatchDate: [
            { required: true, type: 'date', message: 'Please select the date', trigger: 'change' }
          ],
          ETA: [
            { required: true, type: 'date', message: 'Please select the date', trigger: 'change' }
          ],
          tracking: [
            { required: true, message: 'The tracking number cannot be empty', trigger: 'blur' }
          ],
          shippingFee: [
            { required: true, message: 'The shipping fee cannot be empty', trigger: 'blur' }
          ],
          invoice: [
            { required: true, message: 'The invoice cannot be empty', trigger: 'blur' }
          ],
          invoiceDate: [
            { required: true, type: 'date', message: 'Please select the date', trigger: 'change' }
          ],
          invoiceAttachment: [
            { required: true, message: 'The attachment cannot be empty', trigger: 'blur' }
          ],
//          notes: [
//            { required: true, message: 'Please enter a personal introduction', trigger: 'blur' },
//            { type: 'string', min: 20, message: 'Introduce no less than 20 words', trigger: 'blur' }
//          ]
        },
        defaultList: [
//          {
//            name: 'Marco invoice.pdf',
//            default_img: 'pdf'
//          },
//          {
//            name: 'Marco2 invoice.pdf',
//            default_img: 'pdf'
//          },
//          {
//            name: 'Marco3 invoice.pdf',
//            default_img: 'pdf'
//          },
//          {
//            name: 'Marco4 invoice.xlsx',
//            default_img: 'excel'
//          },
//          {
//            name: 'Marco35invoice.xlsx',
//            default_img: 'excel'
//          }
        ],
        uploadList: [],
      }
    },

    computed:{
      ...mapState([ 'curWaitToShipData'])
    },
    created () {
//      let imgObj = {};
//      imgObj.name = '7eb99afb9d5f317c912f08b5212fd69a';
//      imgObj.url = this.shipmentForm.invoiceAttachment
//      this.defaultList[0] = imgObj;
    },
    mounted () {
      this.uploadList = this.$refs.upload.fileList;
    },
    methods: {
      submitShipFrom (name) {
        var subObj = {};
        this.$refs[name].validate((valid) => {
          if (valid) {
            //When shipment submit successful, wait-to-ship remove shipped's items
            this.shipmentList.forEach((shipmentItem, shipmentItemIndex) => {
              if (shipmentItemIndex < this.shipmentList.length) {
                this.curWaitToShipData.forEach((item, index) => {
                  if (shipmentItem.tag == item.tag) {
                    this.curWaitToShipData.splice(index, 1);
                  }
                })
              }
            });
            createShipment(subObj).then(res => {
              this.$Loading.start();
              let resObj = res.data;
              if (resObj.status_code == 1) {
                this.$Loading.finish();
                this.tableDataloading = false;
                this.createShipmentSuccessful = true;
              } else {
                this.$Loading.error();
                this.modalInstance('error', 'Error', 'Create shipment fail!');
              }
            });
            this.$Message.success('Success!');
          } else {
            this.$Message.error('Fail!');
          }
        });
      },
      submitEditShipFrom (name) {
        var subObj = {};
        this.$refs[name].validate((valid) => {
          if (valid) {
            //When shipment submit successful, wait-to-ship remove shipped's items
            this.shipmentList.forEach((shipmentItem, shipmentItemIndex) => {
              if (shipmentItemIndex < this.shipmentList.length) {
                this.curWaitToShipData.forEach((item, index) => {
                  if (shipmentItem.tag == item.tag) {
                    this.curWaitToShipData.splice(index, 1);
                  }
                })
              }
            });
            createShipment(subObj).then(res => {
              this.$Loading.start();
              let resObj = res.data;
              if (resObj.status_code == 1) {
                this.$Loading.finish();
                this.tableDataloading = false;
                this.editShipmentSuccessful = true;
              } else {
                this.$Loading.error();
                this.modalInstance('error', 'Error', 'Create shipment fail!');
              }
            });
            this.$Message.success('Success!');
          } else {
            this.$Message.error('Fail!');
          }
        });
      },
      handleRemove (file) {
        const fileList = this.$refs.upload.fileList;
//        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
        this.uploadList.splice(fileList.indexOf(file), 1);
      },
      handleSuccess (res, file, fileList) {
      	console.log(file)
      	console.log('fileList',fileList)
//        this.shipmentForm.invoiceAttachment = res.data.small_image.url;
        this.uploadList = res.data;
        console.log('uploadList', this.uploadList)
      },
      handleFormatError (file) {
        this.modalInstance('error', 'The file format is incorrect', 'File format of ' + file.name + ' is incorrect, please select jpg or png.');
      },
      handleBeforeUpload () {
        this.$refs.upload.clearFiles();
        const check = this.uploadList.length < 5;
        if (!check) {
          this.modalInstance('warning', 'Warning', 'Up to five files can be uploaded.');
        }
        return check;
      },
      goBack(router) {
        this.createShipmentSuccessful = false;
        this.editShipmentSuccessful = false;
        this.$router.push(router)
      }
    },
    watch: {
      shipmentForm: function (val) {
//        console.log('this.shipmentForm val', val.invoiceAttachment)
//        let imgObj = {};
//        imgObj.name = '7eb99afb9d5f317c912f08b5212fd69a';
//        imgObj.url = val.invoiceAttachment
//        this.defaultList[0] = imgObj;
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../assets/sass/mixin.scss';
  .shipment-form {
    text-align: left;
  }

  .invoice-wrapper {
    @include fj(flex-start);
    margin-bottom: 15px;
  }
  .invoice-attachment {
    width: 80px;
    height: 80px;
    margin-right: 10px;
  }
  .invoice-attachment-file {
    @include fj;
    overflow: hidden;
    position: relative;
    width: 100%;
    height: 100%;
    text-align: center;
    img {
      margin: 0 auto;
    }
    .invoice-attachment-icons {
      display: none;
      position: absolute;
      width: 100%;
      height: 100%;
      padding: 0;
      color: #fff;
      left: 0;
      top: 0;
      z-index: 2;
      background-color: rgba(0, 0, 0, 0.6);
      .icon {
        margin: 0 auto;
        font-size: 25px;
        font-weight: bold;
        cursor: pointer;
      }
    }
    &:hover {
      .invoice-attachment-icons {
        @include fj;
      }
    }
  }
  .invoice-attachment-name {
    overflow: hidden;
    width: 100%;
    padding: 0 !important;
    white-space:nowrap;
    text-overflow:ellipsis;
    -o-text-overflow:ellipsis;
    font-size: 12px;
    text-align: center;
  }
  .upload-wrapper {
    margin-top: 10px;
  }
</style>

